package com.qitmiaojie.controller.chat;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qitmiaojie.controller.utils.Result;
import com.qitmiaojie.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * @author miaojie
 * @version 1.0
 * @description TODO
 * @date 2023/3/8 13:23
 */
@RestController
@RequestMapping("/api/chatbot")
@Slf4j
public class ChatController {


    @Autowired
    private ChatService chatService;

    @GetMapping
    public Result chat(String input) throws IOException {
        log.info("----------------------------------------\n" + input);
        URL url = new URL("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + input);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        String res = "";
        ChatResp chatResp = null;
        StringBuffer buffer = new StringBuffer();
        if (200 == urlCon.getResponseCode()) {
            log.info(urlCon.getResponseMessage());
            InputStream is = urlCon.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String str = null;
            while ((str = br.readLine()) != null) {
                buffer.append(str);
            }
            log.info(buffer.toString());
            chatResp = new ObjectMapper().readValue(buffer.toString(), ChatResp.class);
            System.out.println(chatResp);

        }
        return Result.success(chatResp);
    }

    @PostMapping("/chatgpt")
    public Result chatgpt(String input) throws IOException {

        return chatService.chat(input);
    }

    @PostMapping("/chatgpt2")
    public Result chat(@RequestBody RequestMessage requestMessage){
        log.info(requestMessage.toString());
        return chatService.chatgpt(requestMessage);

    }
}
